<%@ page import="com.tianxiabuyi.persist.QBuilder" %>
<%@ page import="com.tianxiabuyi.utils.JSONUtil" %>
<%@ page import="com.tianxiabuyi.utils.Tools" %>
<%@ page import="com.xiaomi.xmpush.server.Constants" %>
<%@ page import="com.xiaomi.xmpush.server.Result" %>
<%@ page import="com.xiaomi.xmpush.server.Sender" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Objects" %><%--
  Created by IntelliJ IDEA.
  User: lujw
  Date: 2017/6/15
  Time: 17:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="UTF-8" language="java" %>
<%!

    private static final String APP_SECRET_KEY = "ZjjaqXl9xws1O/VXdZ25Mw==";
    private static final String PACKAGE_NAME = "com.tianxiabuyi.hospital";

    /**
     * 通知类型的hospital默认为0
     */
    private static final Integer NOTICE_CATEGORY_HOSPITAL = 0;

    /**
     * false表示上线版本，true表示测试版本
     */
    private static Boolean isDev = null;

    /**
     * 格式化通知列表结果
     * @param noticeList
     * @param hospital
     */
    public void formatNoticeListResult(List<Map> noticeList, Integer hospital) {
        StringBuilder builder = new StringBuilder("-1");
        for (int i = 0, length = noticeList.size(); i < length; i++) {
            Map map = noticeList.get(i);
            Map jsonMap = JSONUtil.mapFromJson(Tools.getDesc(map.remove("json"), ""));
            if (Objects.nonNull(jsonMap))
                map.put("level_color", Tools.getDesc(jsonMap.get("color"), ""));
            else
                map.put("level_color", "");
            List attachList = JSONUtil.listFromJson(Tools.getDesc(map.remove("attachment"), "[]"));
            map.put("attachment", Objects.isNull(attachList) ? Collections.EMPTY_LIST : attachList);
            builder.append(",");
            builder.append(map.get("id"));
        }
        List<Map> commentList = QBuilder.db("basedb").queryHql("select new map(noticeId as notice_id, count(id) as num) from HospitalNoticeComment where noticeId in (" + builder.toString() + ") and hospital = " + hospital + " and status = " + ConstantUtil.STATUS_ENABLE + " group by noticeId");
        List<HospitalNoticeFeedback> feedbackList = QBuilder.db("basedb").queryHql("from HospitalNoticeFeedback where noticeId in (" + builder.toString() + ")  and hospital = " + hospital + " and status = " + ConstantUtil.STATUS_ENABLE);
        for (int i = 0, length = noticeList.size(); i < length; i++) {
            Map map = noticeList.get(i);
            map.put("comment_num", 0);
            Integer notice_id = Tools.getInt(String.valueOf(map.get("id")));
            if ((Integer)map.get("is_comment") == 1) {
                for (int j = 0, cLength = commentList.size(); j < cLength; j++) {
                    Map commentMap = (Map)commentList.get(j);
                    if (notice_id.equals(commentMap.get("notice_id"))) {
                        map.put("comment_num", commentMap.get("num"));
                        break;
                    }
                }
            }
            Integer readNum = 0;
            Integer totalNum = 0;
            for (int j = 0, fLength = feedbackList.size(); j < fLength; j++) {
                HospitalNoticeFeedback feedback = feedbackList.get(j);
                if (notice_id.equals(feedback.getNoticeId())) {
                    if (Objects.nonNull(feedback.getReadTime()) && !"".equals(feedback.getReadTime())) {
                        readNum++;
                    }
                    totalNum++;
                }
            }
            map.put("total_num", totalNum);
            map.put("read_num", readNum);
        }
    }

    /**
     * 补全列表中的员工科室
     * @param list
     * @param hospital
     */
    public void completeUserDept(List<Map> list, Integer hospital) {
        if (Objects.isNull(list))
            return;
        for (int i = 0, length = list.size(); i < length; i++) {
            Map map = list.get(i);
            map.put("dept", UserUtil.getUserDept(hospital, (Integer)map.get("user_id")));
        }
    }

    /**
     * iOS推送
     * @param isDev false表示上线版本，true表示测试版本
     * @param uidList
     * @param hospitalNotice
     */
    public void pushIOS(boolean isDev, List<String> uidList, HospitalNotice hospitalNotice) {
        push(isDev, uidList, hospitalNotice, "iOS");
    }

    /**
     * Android小米推送
     * @param uidList
     * @param hospitalNotice
     * @return
     * @throws Exception
     */
    public void pushAndroid(List<String> uidList, HospitalNotice hospitalNotice){
        push(false, uidList, hospitalNotice, "Android");
    }

    /**
     * 推送所有
     * @param isDev
     * @param uidList
     * @param hospitalNotice
     */
    public void pushAll(boolean isDev, List<String> uidList, HospitalNotice hospitalNotice) {
        push(isDev, uidList, hospitalNotice, "All");
    }

    /**
     * 推送
     * @param isDev false表示上线版本，true表示测试版本
     * @param uidList
     * @param hospitalNotice
     * @param type
     */
    public void push(final boolean isDev, final List<String> uidList, final HospitalNotice hospitalNotice, String type) {
        if (Objects.isNull(uidList) || Objects.isNull(hospitalNotice) || uidList.size() == 0)
            return;
        //推送时避免推送给自己
        if ("app".equals(hospitalNotice.getFromClient()))
            uidList.remove(hospitalNotice.getOperatorId() + "");
        if ("All".equals(type) || "iOS".equals(type)) {
            Thread iOSPushThread = new Thread(){
                @Override
                public void run() {
                    List<String> tokenList = getDeviceToken(uidList);
                    if (Objects.nonNull(tokenList) && tokenList.size() > 0) {
                        HashMap<String, Object> param = new HashMap<String, Object>();
                        param.put("hospital", "");
                        param.put("app_type", "hospital");
                        param.put("tokens", tokenList);
                        param.put("alert", "您有一条新消息\n" + hospitalNotice.getTitle());
                        param.put("id", hospitalNotice.getId());
                        if (isDev)
                            PushUtil.pushDev(param);
                        else
                            PushUtil.push(param);
                    }
                }
            };
            iOSPushThread.start();
        }
        if ("All".equals(type) || "Android".equals(type)) {
            Thread androidPushThread = new Thread(){
                @Override
                public void run() {
                    Constants.useOfficial();
                    Sender sender = new Sender(APP_SECRET_KEY);
                    String messagePayload = hospitalNotice.getTitle();
//                    String title = hospitalNotice.getTitle();
                    String title = "您有一条新消息";
                    String description = hospitalNotice.getTitle();
                    com.xiaomi.xmpush.server.Message message = new com.xiaomi.xmpush.server.Message.Builder()
                            .title(title)
                            .description(description)
                            .payload(messagePayload)
                            .restrictedPackageName(PACKAGE_NAME)
                            .notifyType(1)     // 使用默认提示音提示
                            .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_ACTIVITY)
                            .timeToLive(1 * 24 * 60 * 60 * 1000)
                            .extra(Constants.EXTRA_PARAM_INTENT_URI,
                                    "intent:#Intent;component=com.tianxiabuyi.hospital/.message.activity.MessageDetailActivity;S.id=" + hospitalNotice.getId() + ";end")
                            .build();
                    // 发送
                    Result result = null;
                    int pushNumber = 0;
                    while(true && pushNumber <= 5) {
                        try {
                            result = sender.sendToUserAccount(message, uidList, uidList.size() + 1); //根据accountList, 发送消息到指定设备上
                            break;
                        } catch (IOException e1) {
                            pushNumber ++;
                        } catch (org.json.simple.parser.ParseException e1) {
                            pushNumber ++;
                        }
                    }
                }
            };
            androidPushThread.start();
        }
    }

    /**
     * 根据uid列表获取deviceToken列表
     * @param uidList
     * @return
     */
    public List<String> getDeviceToken(List<String> uidList) {
        if (Objects.isNull(uidList) || uidList.size() == 0)
            return null;
        StringBuilder builder = new StringBuilder();
        for (String uid:uidList) {
            builder.append(uid);
            builder.append(",");
        }
        List<Map<String, String>> uidTokenList = QBuilder.db("basedb").select("new map(concat(u.id, '') as id, d.token as token)").from("HospitalDeviceToken d, HospitalUser u").where(new Where("u.id in (" + builder.substring(0, builder.length() - 1) + ")").and("d.uid=u.id").and("u.status=", ConstantUtil.STATUS_ENABLE).and("d.status=", ConstantUtil.STATUS_ENABLE)).order("d.mTime", QBuilder.desc).query().getResultObj();
        return new ArrayList<String>(remove(uidTokenList));
    }

    /**
     * 去除重复的用户，重复的token
     * @param list
     * @return
     */
    public Set<String> remove(List<Map<String, String>> list) {
        if (Objects.isNull(list) || list.size() == 0)
            return Collections.EMPTY_SET;
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> temp = list.get(i);
            String id = temp.get("id");
            if (map.get(id) == null)
                map.put(id, temp.get("token"));
        }
        return new HashSet<String>(map.values());
    }

    /**
     * 判断当前环境
     * @param input
     * @return
     */
    public boolean isDev(Input input) {
        HttpServletRequest request = input.getRequest();
        String server = request.getServerName();
        if ("apieee.tianxiabuyi.com".equals(server) || "api.eeesys.com".equals(server))
            return false;
        return true;
    }
%>